package cn.schoolwow.util.module.check.jsonarray.flow.check;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;

import java.lang.reflect.Array;
import java.util.Collection;

public class CheckJSONArrayNotEmptyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        JSONArray array = (JSONArray) flowContext.checkData("array");
        String fieldName = (String) flowContext.checkData("fieldName");
        String message = (String) flowContext.checkData("message");

        for(int i=0;i<array.size();i++){
            Object fieldValue = array.getJSONObject(i).get(fieldName);
            if(null==fieldValue){
                throw new IllegalArgumentException(message+"不能为空");
            }
            if(fieldValue.getClass().isArray()){
                if(Array.getLength(fieldValue)==0){
                    throw new IllegalArgumentException(message+"不允许为空");
                }
            }
            if(fieldValue instanceof Collection){
                if(((Collection)fieldValue).isEmpty()){
                    throw new IllegalArgumentException(message+"不允许为空");
                }
            }
        }
    }

    @Override
    public String name() {
        return "实例列表-检查非空数组字段";
    }
}
